import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/cook_db_provider.dart';
import 'package:flutter_douban/config/sqflite/user_db_provider.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/collect/provider/collection_count_model.dart';
import 'package:flutter_douban/model/banner_model.dart';
import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:flutter_douban/tool_views/banner.dart';
import 'package:flutter_douban/tool_views/loading_page.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'cook_recomend_view.dart';

class HomeRecomendPage extends StatefulWidget {
  const HomeRecomendPage({Key? key}) : super(key: key);

  @override
  _HomeRecomendPageState createState() => _HomeRecomendPageState();
}

class _HomeRecomendPageState extends State<HomeRecomendPage>
    with AutomaticKeepAliveClientMixin {
  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;

  /// 列表数组模型
  List<CookInfoModel> _cookInfoList = CookInfoModelList([]).list;
  /// 收藏ids
  List<int> _collectionIDList = [];
  /// 轮播图数据
  List<BannerModel> _bannerList = BannerModelList([]).list;
  StreamSubscription<LoginEvent>? _loginSubscription;
  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  // 获取数据
  Future _getRecommendData({bool replace = true}) async {
    try {
      _collectionIDList = [];
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getHomeRecommendData(page: page, pageSize: 10);
      /// 轮播图数据
      BannerModelList bannerModelList =
          BannerModelList.fromJson(result['result']['banner']);
      /// 获取收藏过得数据
      CookDbProvider provider = new CookDbProvider();
      Database db = await provider.getDataBase();
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? numberId = prefs.getString(AppConfig.numberId);
      List<Map<String, dynamic>> maps = await db.rawQuery(
          "select * from ${provider.name} where ${provider.phoneNum} = $numberId order by ${provider.time} desc");
      CookInfoModelList cookInfoModelList = CookInfoModelList.fromJson(maps);
      for(int i = 0;i< cookInfoModelList.list.length;i++){
        CookInfoModel model = cookInfoModelList.list[i];
        _collectionIDList.add(model.id!);
      }

      /// 列表数据
      List list = [];
      for (Map item in result['result']['list']) {
        list.add(item['r']);
      }
      CookInfoModelList infoList = CookInfoModelList.fromJson(list);
      for(int i = 0;i< infoList.list.length;i++){
        CookInfoModel model = infoList.list[i];
        if(_collectionIDList.contains(model.id)){
          model.is_select = true;
        }else{
          model.is_select = false;
        }
      }
      setState(() {
        page++;
        if (replace) {
          _cookInfoList = infoList.list;
          _bannerList = bannerModelList.list;
        } else {
          _cookInfoList.addAll(infoList.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // Future<void> text() async {
  //   SharedPreferences prefs =
  //       await SharedPreferences.getInstance();
  //   await prefs.setString(AppConfig.numberId, '13161138626');
  // }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // UserDbProvider provider = new UserDbProvider();
    // provider.insert('13161138626', '123456');
    // text();


    // Provider.of<CollectionCookModel>(context,listen: false).update();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();

    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getRecommendData();
      });
    });
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getRecommendData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommendData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: true,
        // 加载时的loading
        firstRefreshWidget:StancePage(),
        // 空视图、异常视图
        // emptyWidget: PageFeedBack(
        //   loading: loading,
        //   error: error,
        //   empty: _songList.isEmpty,
        //   errorMsg: errorMsg,
        //   onErrorTap: () => _easyRefreshController.callRefresh(),
        //   onEmptyTap: () => _easyRefreshController.callRefresh(),
        // ).build(),
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        onLoad: _onLoad,
        child: Column(
          children: [
            Container(
              height: 110,
              child: BannerView(
                bannerList: _bannerList,
              ),
            ),
            ListView.builder(
                controller: _scrollController,
                itemCount: _cookInfoList.length,
                shrinkWrap: true, //增加
                itemBuilder: (BuildContext context, int index) {
                  return CooKRecommendView(
                    model: _cookInfoList[index],
                  );
                })
          ],
        )
    );
  }

  @override
  bool get wantKeepAlive => true;
}
